﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Electure.DAL;

namespace Electure.Admin
{
    public partial class EditCategory : System.Web.UI.Page
    {
        int? Id
        {
            get
            {
                int? res = new int?();
                int id;
                if (int.TryParse(Request.QueryString["id"], out id))
                    res = id;
                return res;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            
            if(Id.HasValue)
            {
                using (var rep = RepositoryFactory.GetCategoryRepository())
                {
                    var category = rep.GetById(Id.Value);
                    tbName.Text = category.Name;
                    tbDescription.Text = category.Description;
                }
            }
        }

        protected void button_Command(object sender, CommandEventArgs e)
        {
            if(e.CommandName == "Save")
            {
                int id;
                using (var rep = RepositoryFactory.GetCategoryRepository())
                {
                    if (Id.HasValue)
                    {
                        rep.Update(new Category()
                        {
                            ID = Id.Value,
                            Name = tbName.Text,
                            Description = tbDescription.Text
                        });
                        id = Id.Value;
                    }
                    else
                    {
                        id = rep.Create(new Category()
                        {
                            Name = tbName.Text,
                            Description = tbDescription.Text
                        });
                    }
                }
                Response.Redirect(string.Format("EditCategory.aspx?id={0}", id));
            }
            else if (e.CommandName == "Cancel")
            {
                Response.Redirect("CategoryList.aspx");
            }
        }

    }
}